package com.mikepenz.presenter.imp;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import com.android.volley.VolleyError;
import com.mikepenz.app.activity.message.MessageDetail;
import com.mikepenz.bean.MessageBean;
import com.mikepenz.interactor.MessageInteactor;
import com.mikepenz.interactor.imp.MessageInteractorImp;
import com.mikepenz.presenter.MessageViewPresenter;
import com.mikepenz.presenter.listener.RequestListener;
import com.mikepenz.utils.CookicUntil;
import com.mikepenz.utils.SystemUtils;
import com.mikepenz.view.MessageView;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2015/10/22.
 */
public class MessageViewPresenterImp implements MessageViewPresenter, RequestListener<List<MessageBean>> {

    MessageView view;
    MessageInteactor inteactor;
    Context context;
    int currentPage = 1;
    List<MessageBean> result;
    boolean isRefresh;

    public MessageViewPresenterImp(Context context) {
        this.context = context;
        this.view = (MessageView) context;
        inteactor = new MessageInteractorImp(context, this);
    }

    @Override
    public void getMessage(boolean isRefresh) {
        this.isRefresh = isRefresh;
        String userId = CookicUntil.getUser().getUserId();
        view.showLoading();
        if (isRefresh) currentPage = 1;
        inteactor.getMessage(userId, currentPage);
    }

    @Override
    public void onClick(int position) {
        Intent intent = new Intent(context, MessageDetail.class);
        MessageBean bean = result.get(position);
        Bundle bundle = new Bundle();
        bundle.putSerializable("message", bean);
        intent.putExtras(bundle);
        context.startActivity(intent);
    }

    @Override
    public void Success(String tag, List<MessageBean> result) {
        view.dimissLoad();
        List<Map<String, Object>> datas = new ArrayList<>();
        for (MessageBean orderBean : result) {
            Map<String, Object> data = SystemUtils.beanToMap(orderBean);
            datas.add(data);
        }
        view.setDate(datas, currentPage == 1);
        view.notifyDateChanged();
        currentPage++;

        if (this.result == null || currentPage == 1)
            this.result = result;
        else
            this.result.addAll(result);
    }


    @Override
    public void Error(String tag, String error) {
        view.dimissLoad();
        view.showError(error);
    }

    @Override
    public void Exception(String tag, VolleyError error) {
        view.dimissLoad();
        view.showError("服务器异常，请稍后重试");
    }
}
